<template>
  <el-scrollbar>
    <div v-if="auditStatus !== MYINDEX_AUDIT_STATUS.SUCCESS" class="absolute top-0 right-10">
      <EditSaveButton :isEdit="isEdit" @buttonClick="buttonClick" />
    </div>
    <div class="form-container mt-5">
      <el-form
        ref="baseFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="150px"
        :size="formSize"
        status-icon
      >
        <el-form-item label="主体类型" required>{{ typeName[userType] }}</el-form-item>
        <el-form-item
          v-if="userType == 'MC01' || userType == 'MC02' || userType == 'MC03'"
          label="经营品类"
          prop="categoryIds"
          :rules="{
            required: true,
            message: '请选择经营品类',
            trigger: 'change',
          }"
        >
          <el-cascader
            v-model="ruleForm.categoryIds"
            placeholder="请选择经营品类"
            style="width: 100%"
            :options="materialCategoryLevelList"
            :show-all-levels="false"
            :collapse-tags="false"
            :props="{
              value: 'value',
              label: 'label',
              multiple: true,
            }"
            :disabled="disabled"
            @change="handleManageRangeChange"
          />
        </el-form-item>
        <el-form-item
          v-if="mainCategoryList"
          label="主营品类"
          prop="mainCategoryId"
          :rules="{
            required: true,
            message: '请选择主营品类',
            trigger: 'change',
          }"
        >
          <el-select v-model="ruleForm.mainCategoryId" placeholder="请选择" :disabled="disabled">
            <el-option
              v-for="item in mainCategoryList"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="userType == 'MC01' || userType == 'MC02' || userType == 'MC03'"
          label="经营品牌"
          prop="manageBrandIds"
          :rules="{
            required: false,
            message: '请选择经营品牌',
            trigger: 'change',
          }"
        >
          <el-select
            v-model="ruleForm.manageBrandIds"
            placeholder="请选择"
            multiple
            filterable
            :clearable="true"
            :disabled="disabled"
          >
            <el-option
              v-for="item in categoryList"
              :key="item.id"
              :label="item.brandName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="品牌" prop="manageBrandIds">
          <div class="flex gap-2">
            <el-tag
              v-for="tag in ruleForm.manageBrandIds"
              :key="tag"
              closable
              :disable-transitions="false"
              @close="handleClose(tag)"
            >
              {{ tag }}
            </el-tag>
            <el-input
              v-if="inputVisible"
              ref="InputRef"
              v-model="inputValue"
              class="w-20"
              size="small"
              :disabled="disabled"
              @keyup.enter="handleInputConfirm()"
              @blur="handleInputConfirm()"
            />
            <el-button
              v-else
              class="button-new-tag"
              size="small"
              :disabled="disabled"
              @click="showInput"
            >
              + 新增
            </el-button>
          </div>
        </el-form-item> -->
        <!-- <el-form-item label="所在商圈/商场" prop="mallName" required>
          <MallSelect
            :disabled="true"
            :defaultMall="defaultMall"
            @onChangeMall="handleChangeMall"
          />
        </el-form-item> -->
        <el-form-item label="营业执照" prop="businessLicenseFile" required>
          <MultiImageUpload
            v-model="ruleForm.businessLicenseFile"
            :limit="1"
            :is-small-upload="true"
            :disabled="disabled"
            @upload-success="handleBusinessLicenseFile"
          />
        </el-form-item>
        <el-form-item label="统一社会信用代码" prop="unifiedSocialCredit" required>
          <el-input v-model="ruleForm.unifiedSocialCredit" :disabled="disabled" />
        </el-form-item>
        <el-form-item label="公司名称" prop="companyName" required>
          <el-input
            v-model="ruleForm.companyName"
            maxlength="150"
            show-word-limit
            :disabled="disabled"
          />
        </el-form-item>
        <el-form-item label="公司别名" prop="companyAlias" required>
          <el-input
            v-model="ruleForm.companyAlias"
            maxlength="32"
            show-word-limit
            :disabled="disabled"
          />
        </el-form-item>
        <el-form-item label="营业地址" prop="businessAddress" required>
          <el-input
            v-model="ruleForm.businessAddress"
            maxlength="150"
            show-word-limit
            :disabled="disabled"
          />
        </el-form-item>
        <el-form-item label="门店地址" prop="storeAddress" required>
          <el-input
            v-model="ruleForm.storeAddress"
            maxlength="64"
            show-word-limit
            :disabled="disabled"
          />
        </el-form-item>
        <el-form-item label="成立日期" required props="licenseValidity">
          <el-date-picker
            v-model="ruleForm.licenseValidity"
            type="date"
            value-format="YYYYMMDD"
            placeholder=""
            style="width: 100%"
            :disabled="disabled"
          />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="商标或品牌授权文件" prop="brandAuthorizationFile">
              <!-- <ImageUpload v-model="ruleForm.brandAuthorizationFile" limit="1" /> -->
              <MultiImageUpload
                v-model="ruleForm.brandAuthorizationFile"
                :limit="1"
                :isSmallUpload="true"
                :disabled="disabled"
                @upload-success="handleBrandAuthorizationFile"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="经营许可文件" prop="businessPermitFile">
              <!-- <ImageUpload v-model="ruleForm.businessPermitFile" limit="1" /> -->
              <MultiImageUpload
                v-model="ruleForm.businessPermitFile"
                :limit="1"
                :isSmallUpload="true"
                :disabled="disabled"
                @upload-success="handleBusinessPermitFile"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="法人授权书" prop="legalAuthorizationFile">
              <div>
                <MultiImageUpload
                  v-model="ruleForm.legalAuthorizationFile"
                  :limit="1"
                  :isSmallUpload="true"
                  :disabled="disabled"
                  @upload-success="handleLegalAuthorizationFile"
                />
                <el-button type="primary" link @click="handleDownTemplate">
                  下载授权委托书模板
                </el-button>
              </div>
            </el-form-item>
          </el-col>
          <!--          <el-col :span="12">
            <el-form-item label="资质证明" prop="qualificationProofFile">
              <MultiImageUpload
                v-model="ruleForm.qualificationProofFile"
                :limit="1"
                :isSmallUpload="true"
                :disabled="disabled"
                @upload-success="handleLegalqualificationProofFile"
              />
            </el-form-item>
          </el-col>-->
        </el-row>
        <!-- --------------------------------- -->
        <!-- <form-title title="法定代表人信息" /> -->
        <!-- <el-form-item label="法定代表人归属地" prop="name">
                <el-select v-model="ruleForm.name" placeholder="请选择">
                    <el-option label="法定代表人" value="法定代表人" />
                    <el-option label="执行事务合伙人" value="执行事务合伙人" />
                </el-select>
            </el-form-item> -->
        <el-form-item label="身份证图片">
          <el-text type="info" size="small">
            1.请上传中国大陆地区身份证图片，保证图片清晰，身份证大小与图片大小一致
          </el-text>
          <el-text type="info" size="small">2.请上传身份证正反两面图片</el-text>
        </el-form-item>
        <div class="flex gap-1 w-full mb-3">
          <el-form-item label="正面" prop="idCardFrontFile">
            <!-- <ImageUpload v-model="ruleForm.idCardFrontFile" limit="1" tipText="身份证正面" /> -->
            <MultiImageUpload
              v-model="ruleForm.idCardFrontFile"
              :limit="1"
              :isSmallUpload="true"
              :disabled="disabled"
              @uploadSuccess="handleIdCardFrontFile"
            />
          </el-form-item>
          <el-form-item label="反面" prop="idCardBackFile">
            <!-- <ImageUpload v-model="ruleForm.idCardBackFile" limit="1" tipText="身份证反面" /> -->
            <MultiImageUpload
              v-model="ruleForm.idCardBackFile"
              :limit="1"
              :isSmallUpload="true"
              :disabled="disabled"
              @uploadSuccess="handleIdCardBackFile"
            />
          </el-form-item>
        </div>
        <el-form-item label="法人代表姓名" prop="legalRepresentative">
          <el-input v-model="ruleForm.legalRepresentative" :disabled="disabled" />
        </el-form-item>
        <el-form-item label="法人代表身份证号码">
          <el-input v-model="ruleForm.idNumber" :disabled="disabled" />
        </el-form-item>
        <el-form-item label="身份证有效期限">
          <el-date-picker
            v-model="ruleForm.idCardValidity"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYYMMDD"
            :disabled="disabled"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
    </div>
  </el-scrollbar>
</template>

<script setup>
import { validateIdCard } from "@/utils/formvalidate";
import MultiImageUpload from "@/components/Upload/MultiImageUpload.vue";
// 枚举
import { MYINDEX_AUDIT_STATUS } from "@/views/hide/myIndex/enums/index";
import {
  SYSTEM_TYPE_REVERSE_OBJECT,
  COMPANY_PROPERTY_ENUM,
  SUBJECT_TYPE_ENUM,
} from "@/utils/enums/system";
import { useUserStore } from "@/store/modules/user";
import CommonAPI from "@/api/system/common";

const userStore = useUserStore();
const userType = userStore.userInfo.userType;

// 请求
import { getIdCardFaceInfo, getIdCardBackInfo, getBusinessLicenseInfo } from "@/api/system/common";
import { saveOrUpdateMerchantCompany, getCompanyEnterInfo } from "@/api/myIndex/index";
// 组件
import { useCategory } from "@/hooks/useCategory";
import { UserTypeName } from "@/enums/system/UserEnum.js";
const formSize = ref("default");
const proxy = getCurrentInstance();
const typeName = ref(UserTypeName);

/***
 * 表单校验管理
 *
 */
const ruleForm = ref({
  // subjectType: UserTypeEnum.HOME_BUILDING_MATERIALS,
  mallNameId: "",
  mallName: "",
  businessLicenseFile: [],
  unifiedSocialCredit: "",
  companyName: "",
  businessAddress: "",
  idCardFrontFile: [],
  idCardBackFile: [],
  legalRepresentative: "",
  idNumber: "",
  idCardValidity: [],
  legalAuthorizationFile: [],
  qualificationProofFile: [],
  brandAuthorizationFile: [],
  businessPermitFile: [],
  manageBrandIds: [],
  companyAlias: "",
  storeAddress: "",
  mainCategoryId: undefined,
});
const validateSingle = (field) => {
  proxy?.refs?.baseFormRef.validateField(field);
};
function handleBusinessLicenseFile() {
  identifyLicense();
  validateSingle("businessLicenseFile");
}
function handleBrandAuthorizationFile() {
  validateSingle("brandAuthorizationFile");
}
function handleBusinessPermitFile() {
  validateSingle("businessPermitFile");
}
function handleLegalAuthorizationFile() {
  validateSingle("legalAuthorizationFile");
}
function handleLegalqualificationProofFile() {
  validateSingle("qualificationProofFile");
}

function handleIdCardFrontFile() {
  identifyFaceCard();
  validateSingle("idCardFrontFile");
}
function handleIdCardBackFile() {
  identifyBackCard();
  validateSingle("idCardBackFile");
}
function handleDownTemplate() {
  window.open("/static/授权委托书.doc");
}
const rules = ref({
  // subjectType: [{ required: true, message: "请选择主体类型", trigger: "blur" }],
  mallName: [{ required: true, message: "请选择或者填写商圈/商场", trigger: "blur" }],
  businessLicenseFile: [{ required: true, message: "请上传营业执照", trigger: "blur" }],
  unifiedSocialCredit: [{ required: true, message: "请输入统一社会信用代码", trigger: "blur" }],
  companyName: [
    { required: true, message: "请输入公司名称", trigger: "blur" },
    { max: 150, message: "公司名称不能超过150个字", trigger: "blur" },
  ],
  companyAlias: [
    { required: true, message: "请输入公司别名", trigger: "blur" },
    { max: 150, message: "公司别名不能超过32个字", trigger: "blur" },
  ],
  businessAddress: [
    { required: true, message: "请输入营业地址", trigger: "blur" },
    { max: 150, message: "营业地址不能超过150个字", trigger: "blur" },
  ],
  storeAddress: [
    { required: true, message: "请输入门店地址", trigger: "blur" },
    { max: 64, message: "门店地址不能超过64个字", trigger: "blur" },
  ],
  brandAuthorizationFile: [
    { required: false, message: "请上传商标或品牌授权文件", trigger: "blur" },
  ],

  businessPermitFile: [{ required: false, message: "请上传经营许可文件", trigger: "blur" }],
  legalAuthorizationFile: [{ required: false, message: "请上传法人授权书", trigger: "blur" }],
  qualificationProofFile: [{ required: false, message: "请上传资质证明", trigger: "blur" }],
  delivery: [{ required: true, message: "请选择营业期限", trigger: "blur" }],
  region: [{ required: true, message: "请输入街道地址、门牌号", trigger: "blur" }],
  licenseValidity: [{ required: true, message: "请选择营业期限", trigger: "blur" }],
  legalRepresentative: [{ required: false, message: "请输入法人代表姓名", trigger: "blur" }],
  idNumber: [
    { required: false, message: "请输入法人代表身份证号码", trigger: "blur" },
    { validator: validateIdCard, trigger: "blur" },
  ],
  idCardValidity: [{ required: false, message: "请选择身份证有效期限", trigger: "blur" }],
  idCardFrontFile: [{ required: false, message: "请上传身份证正面", trigger: "blur" }],
  idCardBackFile: [{ required: false, message: "请上传身份证反面", trigger: "blur" }],
});

/**
 *  所在商圈/商场 处理
 *
 */
const defaultMall = ref({
  mallNameId: "",
  mallName: "",
});
const mainCategoryList = ref();
const handleChangeMall = (val) => {
  ruleForm.value.mallName = val.mallName;
  ruleForm.value.mallNameId = val.mallNameId;
};
// 控制按钮，是否编辑
const isEdit = ref(false);
const disabled = computed(() => {
  return isEdit.value ? false : true;
});
const buttonClick = () => {
  // 可以编辑，直接保存
  if (isEdit.value) {
    // 点击了保存按钮
    submitForm();
  } else {
    isEdit.value = !isEdit.value;
  }
};
// 提交表单
const submitForm = async () => {
  let formEl = proxy?.refs?.baseFormRef;
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      let params = {
        mallNameId: ruleForm.value.mallNameId,
      };
      COMPANY_PROPERTY_ENUM.forEach((item) => {
        let value = ruleForm.value[item.fieldName];
        //item.image || item.type === "Array"
        // 如果是数组，就转换为json
        if (Array.isArray(value)) {
          // 如果是图片就过滤下字段
          if (item.image) {
            let filterItem = value.map((imageArray) => {
              return {
                url: imageArray.url,
                name: imageArray.name,
              };
            });
            params[item.fieldName] = JSON.stringify(filterItem);
          } else {
            params[item.fieldName] = JSON.stringify(value);
          }
        } else {
          params[item.fieldName] = ruleForm.value[item.fieldName];
        }
      });
      params.idCardValidity =
        ruleForm.value.idCardValidity && ruleForm.value.idCardValidity.length
          ? ruleForm.value.idCardValidity.join(",")
          : "";
      params.categoryIds =
        backendValues.value && backendValues.value.length ? backendValues.value.join(",") : "";
      params.companyAlias = ruleForm.value.companyAlias;
      params.storeAddress = ruleForm.value.storeAddress;
      params.manageBrandIds =
        ruleForm.value.manageBrandIds && ruleForm.value.manageBrandIds.length
          ? ruleForm.value.manageBrandIds.join(",")
          : "";
      params.mainCategoryId = ruleForm.value.mainCategoryId;
      // params.subjectType = ruleForm.value.subjectType.value;
      console.log(params);
      handleAddMerchantCompany(params);
    } else {
      console.log("error submit!", fields);
    }
  });
};

const handleAddMerchantCompany = async (params) => {
  try {
    if (ruleForm.value?.id) {
      await saveOrUpdateMerchantCompany({ ...params, id: ruleForm.value.id });
    } else {
      await saveOrUpdateMerchantCompany(params);
    }
    ElMessage.success(`${ruleForm.value?.id ? "更新" : "保存"}成功`);
    getDefaultFormFunc();
    isEdit.value = !isEdit.value;
  } catch (err) {
    console.log(err);
  }
};
const backendValues = ref([]);
const categoryList = ref([]);
const handleManageRangeChange = (value) => {
  getBycategoryList(value);
  ruleForm.value.manageBrandIds = [];
  ruleForm.value.mainCategoryId = undefined;
  // 传递给后端的值通常是 value 的最后一项
  backendValues.value = value.map((path) => path[path.length - 1]);
  mainCategoryList.value = materialCategoryLevelList.value.filter((item) => {
    return backendValues.value.includes(item.id);
  });
};

async function getBycategoryList(data) {
  const res = await CommonAPI.getBycategoryId(data);
  categoryList.value = res.data;
}
// 提供一个方法让父组件获取 formRef
const getBaseFormRef = () => {
  return proxy.refs["baseFormRef"];
};
const auditStatus = ref(null);
const reason = ref("");
const getDefaultFormFunc = async () => {
  try {
    const res = await getCompanyEnterInfo(userStore.userInfo.userId);
    const data = res.data;
    if (data) {
      handleDefaultForm(data);
      auditStatus.value = data.status;
      if (data.status === MYINDEX_AUDIT_STATUS.FAILED) {
        reason.value = data.remark;
        openErrorMessage();
      }
    } else {
      isEdit.value = true;
    }
  } catch (err) {
    console.log(err);
  }
};

const openErrorMessage = () => {
  ElNotification({
    title: "驳回原因",
    type: "error",
    message: reason.value,
    duration: 5000,
  });
};
const handleDefaultForm = (data) => {
  ruleForm.value = { ...data };
  ruleForm.value.brandAuthorizationFile = JSON.parse(data.brandAuthorizationFile);
  ruleForm.value.businessPermitFile = JSON.parse(data.businessPermitFile);
  ruleForm.value.legalAuthorizationFile = JSON.parse(data.legalAuthorizationFile);
  ruleForm.value.qualificationProofFile = JSON.parse(data.qualificationProofFile);
  ruleForm.value.businessLicenseFile = JSON.parse(data.businessLicenseFile);
  ruleForm.value.idCardBackFile = JSON.parse(data.idCardBackFile);
  ruleForm.value.idCardFrontFile = JSON.parse(data.idCardFrontFile);
  ruleForm.value.idCardValidity = data.idCardValidity?.split(",");
  ruleForm.value.categoryIds = data.categoryIds.split(",").map((item) => Number(item));
  ruleForm.value.mainCategoryId = data.mainCategoryId;
  backendValues.value = ruleForm.value.categoryIds;
  getBycategoryList(ruleForm.value.categoryIds);
  mainCategoryList.value = materialCategoryLevelList.value.filter((item) => {
    return backendValues.value.includes(item.id);
  });
  if (data.manageBrandIds) {
    ruleForm.value.manageBrandIds = data.manageBrandIds.split(",").map((item) => Number(item));
  }
  ruleForm.value.companyAlias = data.companyAlias;
  ruleForm.value.storeAddress = data.storeAddress;
  defaultMall.value = {
    mallNameId: data.mallNameId,
    mallName: data.mallName,
  };
};
/**
 * ocr 识别
 *
 *
 */
// 身份证正面
const identifyFaceCard = async () => {
  try {
    const data = await getIdCardFaceInfo({
      url: ruleForm.value?.idCardFrontFile[0]?.url,
    });
    ruleForm.value.legalRepresentative = data.data.name;
    ruleForm.value.idNumber = data.data.num;
    validateSingle("legalRepresentative");
    validateSingle("idNumber");
  } catch (err) {
    console.log(err);
  }
};
// 身份证反面
const identifyBackCard = async () => {
  try {
    const data = await getIdCardBackInfo({
      url: ruleForm.value?.idCardBackFile[0]?.url,
    });
    ruleForm.value.idCardValidity = [data.data.startDate, data.data.endDate];
    validateSingle("idCardValidity");
  } catch (err) {
    console.log(err);
  }
};
// 营业执照
const identifyLicense = async () => {
  try {
    const res = await getBusinessLicenseInfo({
      url: ruleForm.value?.businessLicenseFile[0]?.url,
    });
    ruleForm.value.unifiedSocialCredit = res.data.regNum;
    ruleForm.value.companyName = res.data.name;
    ruleForm.value.businessAddress = res.data.address;
    ruleForm.value.licenseValidity = res.data.establishDate;
    console.log(ruleForm.value.licenseValidity);
    validateSingle("unifiedSocialCredit");
    validateSingle("companyName");
    validateSingle("businessAddress");
    validateSingle("licenseValidity");
  } catch (err) {
    console.log(err);
  }
};
const { getMaterialCategory, getSpecialLevelList } = useCategory();

const materialCategoryLevelList = ref([]);

async function getCateList() {
  try {
    const id = userStore.userInfo.userType == "MC02" ? 1 : 2;
    await CommonAPI.getCategoryInfo(id).then((res) => {
      materialCategoryLevelList.value = res.data.map((item) => ({
        label: item.name,
        value: item.id,
        tagType: "info",
        id: item.id,
      }));
    });
  } catch (error) {
    console.error("获取分类失败", error);
  }
}
onMounted(async () => {
  await getMaterialCategory();
  getCateList();
  if (!ruleForm.value.mainCategoryId) {
    ruleForm.value.mallName = userStore.userInfo.mallName;
    ruleForm.value.mallNameId = userStore.userInfo.mallId;
    defaultMall.value = {
      mallNameId: userStore.userInfo.mallId,
      mallName: userStore.userInfo.mallName,
    };
  }
  // materialCategoryLevelList.value = getSpecialLevelList(2);
  getDefaultFormFunc();
});
defineExpose({
  getBaseFormRef,
});
</script>

<style scoped lang="scss">
.form-container {
  width: 70%;
  height: 100%;
}
</style>
